<template>
  <vxe-table
    ref="tableRef"
    id="AwardTable"
    :data="tableData"
    stripe
    border
    show-overflow
    show-header-overflow
    align="center"
    :edit-config="editConfig"
    :column-config="{ resizable: false }"
    :size="vxeTableSize"
    class="custom-table"
  >
    <vxe-column
      field="name"
      :title="t('reviewApplyInfo.awardList.fields.name')"
      :edit-render="textEditRender"
    />
    <vxe-column
      field="awardingUnit"
      :title="t('reviewApplyInfo.awardList.fields.awardingUnit')"
      :edit-render="textEditRender"
    />
    <vxe-column
      field="awardLevel"
      :title="t('reviewApplyInfo.awardList.fields.awardLevel')"
      :edit-render="textEditRender"
    />
    <vxe-column
      field="ranking"
      :title="t('reviewApplyInfo.awardList.fields.ranking')"
      :edit-render="numberEditRender"
    />
    <vxe-column
      field="awardTime"
      :title="t('reviewApplyInfo.awardList.fields.awardTime')"
      :edit-render="{ placeholder: t('common.selectText') }"
    >
      <template #edit="{ row }">
        <el-date-picker
          v-model="row.awardTime"
          type="date"
          :placeholder="t('common.selectText')"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
      </template>
    </vxe-column>
    <!-- 删除按钮 -->
    <vxe-column v-if="!disabled" field="action" :title="t('common.operate')" width="80">
      <template #default="{ row }">
        <el-button type="primary" link @click="removeRow(row)">{{ t('action.delete') }}</el-button>
      </template>
    </vxe-column>
  </vxe-table>
  <!-- 新增行按钮 -->
  <div v-if="!disabled" class="text-center mt-5px">
    <el-button size="small" type="primary" link @click="handleAddRow">
      <Icon icon="ep:plus" :size="12" />{{ t('common.addRow') }}
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { useVxeEditTable } from './useVxeEditTable'
import { AwardRowVO } from '@/api/recruit/reviewApply/types'

defineOptions({ name: 'AwardTable' })

const props = withDefaults(
  defineProps<{
    list: AwardRowVO[]
    disabled?: boolean
  }>(),
  {
    disabled: false
  }
)

const { t } = useI18n() // 国际化

const {
  disabledEdit,
  tableRef,
  editConfig,
  tableData,
  vxeTableSize,
  textEditRender,
  numberEditRender,
  addRow,
  removeRow,
  getTableData
} = useVxeEditTable<AwardRowVO>()

watch(
  () => props.list,
  () => {
    tableData.value = props.list
  },
  { immediate: true, deep: true }
)

watch(
  () => props.disabled,
  () => {
    disabledEdit.value = props.disabled
  },
  { immediate: true, deep: true }
)

// 添加行
const handleAddRow = async () => {
  const record: Omit<AwardRowVO, 'id'> = {
    name: '',
    awardingUnit: '',
    awardLevel: '',
    ranking: '',
    awardTime: ''
  }
  await addRow(record)
}

defineExpose({ getTableData })
</script>
